<?php

class QuestionarioController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
                    array(
                        'allow',
                        'actions'=>array('index','create','update','admin','delete','imprime'),
                        'expression'=>'Yii::app()->user->isAdmin',
                    ),
                    array(
                        'deny',
                        'users'=>array('*'),
                    ),
		);
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'admin' page.
	 */
	public function actionCreate()
	{
		$model=new Questionario;
                $model->situacao = 0;

		$this->performAjaxValidation($model);

                if(isset($_POST['Questionario']))
		{
                    $model->attributes=$_POST['Questionario'];
                    
                    if($model->save())
                        $this->redirect(array('admin'));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
                $this->layout='//layouts/column1';
                
		$model=$this->loadModel($id);
                $eixos = QuestionarioEixo::model()->findAll('id_questionario = :id_questionario',array('id_questionario'=>$id));

		$this->performAjaxValidation($model);
                
		if(isset($_POST['Questionario']))
		{
			$model->attributes=$_POST['Questionario'];
                        
			if($model->save())
                                $this->redirect(array('admin'));
		}
                
                $min = $model->calcMin();
                $max = $model->calcMax();

		$this->render('update',array(
                    'model'=>$model,
                    'eixos'=>$eixos,
                    'min'=>$min,
                    'max'=>$max,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			$altera = $this->loadModel($id);
                        $altera->situacao = 99;
                        $altera->save();

			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$this->redirect(array('admin'));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Questionario('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Questionario']))
			$model->attributes=$_GET['Questionario'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

        public function actionImprime()
        {
            $model=new ImprimeForm;
            $model->tipo = 0;

            if(isset($_POST['ImprimeForm']))
            {
                $model->attributes=$_POST['ImprimeForm'];
                if($model->validate())
                {
                    Yii::import('application.extensions.tcpdf.*');
                    
                    $questionario = Questionario::model()->findByPk($model->id_questionario);
                    $questoes = Questao::model()->findAll('id_questionario = :id_questionario',array(':id_questionario'=>$model->id_questionario));
                    
                    if($model->tipo == 0) //Resumido
                    {
                        $pdf = new SADPDF('P');
                        $pdf->SetCreator('Sistema de Avaliação Diagnóstica');
                        $pdf->SetTitle('QUESTIONÁRIO DE AVALIAÇÃO DIAGNÓSTICA');
                        $pdf->SetPrintHeader(true);
                        $pdf->SetPrintFooter(true);
                        $pdf->SetMargins('20','20','20');
                        $pdf->AddPage();
                        
                        //INFORMAÇÕES GERAIS
                        $txt .= '<p style="font-family: tahoma; font-size: 10pt; text-align: justify;">';
                        $txt .= '<strong>Questionário: </strong>' . $questionario->nome . ' (Versão ' . number_format($questionario->versao,1) . ')<br />';
                        $txt .= '<strong>Descrição: </strong>' . $questionario->descricao . '<br />';
                        $txt .= '</p>';

                        //RESPOSTAS
                        $txt .= '<p style="font-family: tahoma; font-size: 10pt; text-align: justify;"><strong>1. Número de Funcionários</strong><br />R: ____________________<br /></p>';
                        $txt .= '<p style="font-family: tahoma; font-size: 10pt; text-align: justify;"><strong>2. Faturamento da Empresa</strong><br />R: R$ ____________________<br /></p>';

                        foreach($questoes as $k=>$questao)
                        {
                            $txt .= '<p style="font-family: tahoma; font-size: 10pt; text-align: justify;"><strong>'.($k+3).'. '.$questao->descricao_questao.'</strong><br />';
                            
                            foreach($questao->alternativas as $i=>$alternativa)
                            {
                                $txt .= '( &nbsp;&nbsp; ) ' . $alternativa->texto . '<br />';
                            }
                            
                            $txt .= '</p>';
                            
                        }
                        
                        $pdf->writeHTML($txt,true,false,true,false,'');
                        $pdf->Output('questionarioResumido'.date('dmYHis').'.pdf','I');
                    }elseif($model->tipo == 1) //Completo
                    {
                        $pdf = new SADPDF('P');
                        $pdf->SetCreator('Sistema de Avaliação Diagnóstica');
                        $pdf->SetTitle('QUESTIONÁRIO DE AVALIAÇÃO DIAGNÓSTICA');
                        $pdf->SetPrintHeader(true);
                        $pdf->SetPrintFooter(true);
                        $pdf->SetMargins('20','20','20');
                        $pdf->AddPage();
                        
                        //INFORMAÇÕES GERAIS
                        $txt = '';
                        $txt .= '<p style="font-family: tahoma; font-size: 10pt; text-align: justify;">';
                        $txt .= '<strong>Questionário: </strong>' . $questionario->nome . ' (Versão ' . number_format($questionario->versao,1) . ')<br />';
                        $txt .= '<strong>Descrição: </strong>' . $questionario->descricao . '<br />';
                        $txt .= '<strong>Tipo: </strong> Completo<br />';
                        $txt .= '</p>';

                        //RESPOSTAS
                        $txt .= '<p style="font-family: tahoma; font-size: 10pt; text-align: justify;"><strong>1. Número de Funcionários</strong><br />R: ____________________<br /></p>';
                        $txt .= '<p style="font-family: tahoma; font-size: 10pt; text-align: justify;"><strong>2. Faturamento da Empresa</strong><br />R: R$ ____________________<br /></p>';

                        $arrRespostas = array('1'=>'A','2'=>'B','3'=>'C','4'=>'D','5'=>'E','6'=>'F','7'=>'G','8'=>'H','9'=>'I','10'=>'J','11'=>'K','12'=>'L','13'=>'M','14'=>'N','15'=>'O','16'=>'P','17'=>'Q','18'=>'R','19'=>'S','20'=>'T');
                        
                        foreach($questoes as $k=>$questao)
                        {
                            $txt .= '<p style="font-family: tahoma; font-size: 10pt; text-align: justify;"><strong>'.($k+3).'. '.$questao->descricao_questao.'</strong><br /><br />';
                            $txt .= '<table cellpadding="2" border="1" width="100%">';
                            $txt .= '<tr style="background-color: #ccc;">';
                            $txt .= '<th colspan="2" width="95%"><strong>Alternativa</strong></th>';
                            $txt .= '<th width="5%" style="text-align: center;"><strong>FM</strong></th>';
                            $txt .= '</tr>';
                            
                            foreach($questao->alternativas as $i=>$alternativa)
                            {
                                if($i % 2 == 0)
                                    $txt .= '<tr>';
                                else
                                    $txt .= '<tr style="background-color: #e4e4e4;">';
                                    
                                $txt .= '<td width="5%" style="text-align: center;">' . $arrRespostas[$i+1] . '</td>';
                                $txt .= '<td width="90%">' . $alternativa->texto . '</td>';
                                $txt .= '<td width="5%" style="text-align: center;">' . $alternativa->fator_multiplicativo . '</td>';
                                $txt .= '</tr>';
                            }
                            
                            $txt .= '</table>';
                            
                            $txt .= '<br />';
                            
                            $txt .= '<table cellpadding="2" border="1" width="100%">';
                            $txt .= '<tr style="background-color: #ccc;">';
                            $txt .= '<th width="35%"><strong>Eixo</strong></th>';
                            $txt .= '<th width="55%"><strong>Justificativa</strong></th>';
                            $txt .= '<th width="10%" style="text-align: center;"><strong>Peso</strong></th>';
                            $txt .= '</tr>';

                            $eixosQuestao = EixoQuestao::model()->findAll('id_questao = :id_questao',array(':id_questao'=>$questao->id_questao));
                            
                            foreach($eixosQuestao as $i=>$eixo)
                            {
                                if($i % 2 == 0)
                                    $txt .= '<tr>';
                                else
                                    $txt .= '<tr style="background-color: #e4e4e4;">';

                                $txt .= '<td >'.$eixo->eixos->nome_eixo.'</td>';
                                $txt .= '<td>'.$eixo->justificativa.'</td>';
                                $txt .= '<td style="text-align: center;">'.$eixo->peso.'</td>';
                                $txt .= '</tr>';
                            }
                            
                            $txt .= '</table>';
                            $txt .= '</p>';
                            
                            
                        }
                        
                        $pdf->writeHTML($txt,true,false,true,false,'');
                        $pdf->Output('questionarioResumido'.date('dmYHis').'.pdf','I');
                    }
                }
            }else
            {
                $this->render('imprime',array('model'=>$model));
            }
        }        

        /**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Questionario::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
        
	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='questionario-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
